package com.bwt.top.bwt_ad_flutter.manager;

import android.app.Activity;
import android.content.Context;

import androidx.annotation.NonNull;

import com.bwt.top.bwt_ad_flutter.AdErrorUtil;
import com.bwt.top.bwt_ad_flutter.ad.BwtInterstitialAd;
import com.bwt.top.bwt_ad_flutter.config.BwtAdEventConfig;
import com.bwt.top.bwt_ad_flutter.listener.OnAdReleaseListener;
import com.bwt.top.bwt_ad_flutter.model.AdParams;
import com.bwt.top.bwt_ad_flutter.util.LogUtil;
import com.bwt.top.exception.AdError;

import java.util.HashMap;
import java.util.Map;

/**
 * 插屏广告管理器
 */
public class BwtInterstitialAdManager implements OnAdReleaseListener {
    private static BwtInterstitialAdManager instance;
    private final Map<String, BwtInterstitialAd> bwtInterstitialAdMap = new HashMap<>();

    private BwtInterstitialAdManager() {
        BwtAdManager.getInstance().registerOnAdReleaseListener(this);
    }

    public static BwtInterstitialAdManager getInstance() {
        if (instance == null) {
            synchronized (BwtInterstitialAdManager.class) {
                if (instance == null) {
                    instance = new BwtInterstitialAdManager();
                }
            }
        }
        return instance;
    }

    @Override
    public void onAdRelease(String adId) {
        release(adId);
    }

    /**
     * 检查并加载展示热启动插屏广告
     *
     * @param adParams     广告参数
     * @param loadThenShow 获取成功是否立即展示
     */
    public void loadInterstitialAd(Context context, @NonNull AdParams adParams, boolean loadThenShow) {
        LogUtil.log("插屏广告加载预备, adId: " + adParams.getAdId());
        if (!(context instanceof Activity) || ((Activity) context).isFinishing()) {
            LogUtil.log("插屏广告加载失败, adId: " + adParams.getAdId() + ", error: 当前上下文不适合获取插屏广告!");
            BwtAdManager.getInstance().postAdEvent(BwtAdEventConfig.KEY_AD_EVENT_ON_AD_FAILED, adParams, AdErrorUtil.getError(new AdError(-1, "当前上下文不适合获取插屏广告")));
            return;
        }

        BwtInterstitialAd bwtInterstitialAd = new BwtInterstitialAd(adParams, (Activity) context, loadThenShow);
        bwtInterstitialAdMap.put(adParams.getAdId(), bwtInterstitialAd);
        bwtInterstitialAd.loadAd();
    }

    /**
     * 展示插屏广告
     */
    public void showInterstitialAd(@NonNull AdParams adParams) {
        BwtInterstitialAd bwtInterstitialAd = bwtInterstitialAdMap.get(adParams.getAdId());

        if (bwtInterstitialAd != null) {
            bwtInterstitialAd.showInterstitialAd();
        }
    }

    /**
     * 释放广告
     */
    private void release(String adId) {
        if (adId == null) return;
        try {
            BwtInterstitialAd bwtInterstitialAd = bwtInterstitialAdMap.get(adId);
            if (bwtInterstitialAd != null) {
                bwtInterstitialAd.release();
                bwtInterstitialAdMap.remove(adId);
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
}
